package com.frame.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.frame.Page;
import com.frame.Result;
import com.frame.domain.Menu;
import com.frame.domain.MenuPermission;
import com.frame.domain.Permission;
import com.frame.domain.RolePermission;
import com.frame.service.MenuPermissionService;
import com.frame.service.MenuService;
import com.frame.service.PermissionService;
import com.frame.support.Tree;
import com.mini.core.utils.StrKit;

/**
 * @author sxjun1904
 * @since 2016-8-8
 */
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController{

    private static final Logger log = LoggerFactory.
            getLogger(MenuController.class);

    @Autowired
    private MenuService menuService;
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private MenuPermissionService menuPermissionService;

    /**
     * 菜单页面
     * @param model
     * @param request
     * @param response
     * @param treeId
     * @return
     */
    @RequiresPermissions("menu:list")
    @RequestMapping(value = "list")
    public String list(Model model, HttpServletRequest request, HttpServletResponse response,String treeId) {
    	Page<Menu> page = menuService.paginateResult(new Page<Menu>(request, response),treeId);
    	addPage(model,page);
        return "menu/menuList";
    }
    
    /**
     * 菜单表单页面
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value = "form")
    public String form(Model model, HttpServletRequest request, HttpServletResponse response,String id) {
    	if(StrKit.notBlank(id)){
    		Menu m = menuService.findById(id);
    		model.addAttribute("menu", m);
    	}
        return "menu/menuForm";
    }
    
    /**
     * 菜单授权
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value = "authorize")
    public String authorize(Model model, HttpServletRequest request, HttpServletResponse response,String id) {
    	model.addAttribute("menuid", id);
        return "menu/authorizeForm";
    }
    
    /**
     * 保存菜单
     * @param menu
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(Menu menu) {
    	if(Tree.TREE_ROOT_ID.equals(menu.getParentid()))
    		menu.setParentid(null);
    	if(StrKit.notBlank(menu.getId()))
    		menuService.update(menu);
    	else{
    		menu.setCreatetime(new Date());
        	menuService.save(menu);
    	}
        return success();
    }
    
    /**
     * 菜单授权保存
     * @param menuperm
     * @return
     */
    @RequestMapping(value = "authorizesave")
    @ResponseBody
    public Result authorizesave(MenuPermission menuperm) {
    	if(Tree.TREE_ROOT_ID.equals(menuperm.getPermissionid()))
    		return error();
    	menuPermissionService.deleteByMenuid(menuperm.getMenuid());
    	menuperm.setId(UUID.randomUUID().toString());
    	menuperm.setCreatetime(new Date());
    	menuPermissionService.save(menuperm);
        return success();
    }
    
    /**
     * 删除菜单
     * @param id
     * @return
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    public Result delete(String id) {
    	menuService.delete(id);
        return success();
    }
    
    /**
     * 获取菜单树
     * @return
     */
    @RequestMapping(value = "tree")
    @ResponseBody
    public List<Tree> tree() {
    	List<Menu> menus= menuService.findAll();
    	List<Tree> trees = new ArrayList<Tree>();
    	Tree root = new Tree();
    	root.setId(Tree.TREE_ROOT_ID);
    	root.setName("菜单树");
    	root.setOpen(true);
    	trees.add(root);
    	for(Menu menu : menus){
    		Tree tree = new Tree();
    		tree.setId(menu.getId());
    		tree.setName(menu.getName());
    		if(StrKit.isBlank(menu.getParentid())){
    			tree.setpId(Tree.TREE_ROOT_ID);
	    		tree.setOpen(true);
    		}else
    			tree.setpId(menu.getParentid());
    		trees.add(tree);
    	}
    	return trees;
    }
    
    /**
     * 菜单权限树
     * @param menuid
     * @return
     */
    @RequestMapping(value = "permtree")
    @ResponseBody
    public List<Tree> permtree(String menuid) {
 	    List<Permission> perms = permissionService.findAll();
 	    List<MenuPermission> menuperms = null;
 	    if(StrKit.notBlank(menuid))
 	    	menuperms = menuPermissionService.findByMenuId(menuid);
 	    List<Tree> trees = new ArrayList<Tree>();
 		for(Permission perm : perms){
 			if("0".equals(perm.getPermtype())||"1".equals(perm.getPermtype())){
	 			Tree tree = new Tree();
	 			tree.setId(perm.getId());
	 			tree.setName(perm.getPermname());
	 			if(StrKit.notBlank(perm.getParentid()))
	 				tree.setpId(perm.getParentid());
	 			else
	 				tree.setOpen(true);
	 			if(menuperms!=null)
	 				for(MenuPermission menuperm:menuperms){
	 					if(menuperm.getPermissionid().equals(perm.getId())){
	 						tree.setChecked(true);
	 						break;
	 					}
	 				}
	 			trees.add(tree);
 			}
 		}
 		return trees;
    }
    
}
